﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Web;
using System.Web.UI.HtmlControls;

public partial class Hipocrate_Reports : SessionPageBase
{
    private static string tempID;
    private static bool bChecked;
    private static bool bCheckedSum;
    private static bool bCheckedFormula;
    private static bool bCheckedSpan;

    public string TempID
    {
        get { return tempID; }
        set { tempID = value; }
    }
    public string UserIDx
    {
        get { return this.Master.GetUserID(); }
    }

    public CustomControlsNS.CustomButton GetButton(string buttonID)
    {
        return this.Master.GetButton(buttonID);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
		this.Context.Trace.Write("event handler called", "Page_Load");
		CustomControlsNS.CustomButton cc = new CustomControlsNS.CustomButton(Resources.DatabaseStrings.btn_Save, Resources.DatabaseStrings.btn_Save, "$get('" + btnSaveReport.ClientID + "').click();", "1", true);
        cc.ID = "btn_SaveX";
        this.Master.PageToolbarButtons.Add(cc);

        if (!IsPostBack)
        {
            Session["ds_ReportDetails"] = null;
        }

        if (!IsPostBack)
        {
            LoadReportsCustom(sender);
			LoadDropDown(drpCategory, null);
            extStart_Date.SelectedDate = System.DateTime.Now;
            extEnd_Date.SelectedDate = System.DateTime.Now;
        }
		LoadValuesFromFormCollection();
    }

	void LoadValuesFromFormCollection()
	{
		//Form[ctl00$ContentPlaceHolderContent$TabContainer1$tab2$rptParentView$ctl02$ChildRepeater$ctl02$txtID] = dummy
		foreach (RepeaterItem item in rptParentView.Items)
		{
			Repeater ChildRepeater = item.FindControl("ChildRepeater") as Repeater;
			foreach (RepeaterItem report in ChildRepeater.Items)
			{
				Table tblCriterias = report.FindControl("tblCriterias") as Table;
				foreach (TableRow tr in tblCriterias.Rows)
					if (tr.Cells.Count > 1)
						foreach (Control c in tr.Cells[1].Controls)
							if (this.Request.Form[c.UniqueID] != null)
							{
								if (c is TextBox)
									(c as TextBox).Text = this.Request.Form[c.UniqueID];
								else
									if (c is DropDownList)
									{
										//startDate.Text += "<br/>" + c.UniqueID + " -- " + this.Request.Form[c.UniqueID];
										(c as DropDownList).SelectedValue = this.Request.Form[c.UniqueID];
									}
							}
			}
		}
	}

    private void DoSelectReport(string strRptID, Table tbl)
    {
        ViewState["RptID"] = strRptID;
        DataSet ds_ReportDetails = Hipocrate.DB.DBConnection.GetData("GetReportCustom", new string[] { "UserID", "ID" }, new object[] { 1, ViewState["RptID"] }); // TODO: real user id!
        Session["ds_ReportDetails"] = ds_ReportDetails;

        if (ds_ReportDetails != null)
			LoadCriterias(strRptID, tbl);
    }

    protected void DoView(Hashtable ht)
    {
        string strCriterias = "";
        foreach (string strKey in ht.Keys)
            if (((string[])ht[strKey])[0] != "")
                strCriterias += Tools.GetHeaderText(strKey) + " = '" + ((string[])ht[strKey])[1] + "', ";
        strCriterias = (strCriterias.Length > 0) ? strCriterias.Substring(0, strCriterias.Length - 2) : strCriterias;
        strCriterias = (strCriterias.Length > 0) ? "( " + strCriterias + " )" : strCriterias;
        lblCriterias.Text = strCriterias;

        DataSet ds = (DataSet)Session["ds_ReportDetails"];
        DataView dv0 = ds.Tables[0].DefaultView;
        DataView dv2 = ds.Tables[2].DefaultView;
        DataView dv4 = ds.Tables[4].DefaultView;
        string strRptID = dv0[0]["ID"].ToString();
        string strRptName = dv0[0]["Name_" + Tools.GetLanguage(Request)].ToString();
        string strProcedureName = dv0[0]["ProcedureName"].ToString();
        string strDatabaseName = dv0[0]["DatabaseName"].ToString();
        dv4.RowFilter = "[PARAMETER_NAME] <> '@RETURN_VALUE' AND [PARAMETER_NAME] <> '@TABLE_RETURN_VALUE'";

        string[] arParamNames = new string[dv4.Count];
        object[] arParamValues = new object[dv4.Count];
        ArrayList arParamNamesAndValues = new ArrayList();
        for (int i = 0; i < dv4.Count; ++i)
        {
            arParamNames[i] = dv4[i]["PARAMETER_NAME"].ToString().Substring(1);
            arParamValues[i] = Tools.GetSQLValue((ht != null && ht[arParamNames[i]] != null ? ((string[])ht[arParamNames[i]])[0] : ""), dv4[i]["TYPE_NAME"].ToString(), Tools.GetLanguage(Request));
            if (arParamNames[i] == "UserID" && arParamValues[i] == System.DBNull.Value)
                arParamValues[i] = this.UserIDx;
            if (arParamValues[i] != System.DBNull.Value)
                arParamNamesAndValues.Add("@" + arParamNames[i] + "=" + arParamValues[i].ToString());
        }
        string[] arParamNamesAndValues2 = new string[arParamNamesAndValues.Count];
        arParamNamesAndValues.CopyTo(arParamNamesAndValues2);

        int nResult = 0;
        DateTime dt1 = DateTime.Now;
        DateTime dt2 = DateTime.Now;
        DataSet ds1 = null;
        try
        {
            dt1 = DateTime.Now;
            ds1 = Hipocrate.DB.DBConnection.GetData(strProcedureName, arParamNames, arParamValues, strDatabaseName, GetProcedureType(strProcedureName, strDatabaseName));
            dt2 = DateTime.Now;
            Session["ds_ReportResult"] = ds1;

            GridViewReportDetails.SessionKey = "ds_ReportResult";
            GridViewReportDetails.SessionKeyIndex = 0;
            GridViewReportDetails.SessionKeyFilter = ds1.Tables[0].DefaultView.RowFilter;
            GridViewReportDetails.CaptionForXLS = strRptName;
            GridViewReportDetails.SessionKeyColumnHeadersIndex = 1;
            if (dv0[0]["PageSize"] != System.DBNull.Value && dv0[0]["PageSize"].ToString() != "")
            {
                GridViewReportDetails.AllowPaging = true;
                GridViewReportDetails.PageSize = Convert.ToInt32(dv0[0]["PageSize"]);
            }
            else
            {
                GridViewReportDetails.AllowPaging = false;
                GridViewReportDetails.PageSize = -1;
            }

            GridViewReportDetails.HiddenColumns = dv0[0]["HiddenColumns"].ToString().Split(new char[] { ',' });
            GridViewReportDetails.TotalColumns = dv0[0]["TotalColumns"].ToString();
            GridViewReportDetails.TotalOnAllDecimalColumns = Convert.ToBoolean(dv0[0]["TotalOnAllDecimalColumns"]);

            GridViewReportDetails.LinkColumn = Tools.GetArrayFromColumn(dv2, "LinkColumn");
            GridViewReportDetails.LinkFormat = Tools.GetArrayFromColumn(dv2, "LinkFormat");
            GridViewReportDetails.LinkFields = Tools.GetArrayFromColumn(dv2, "LinkFields");
            GridViewReportDetails.LinkInNewWindow = Tools.GetArrayFromColumn(dv2, "LinkInNewWindow");

            GridViewReportDetails.DataSource = ds1.Tables[0].DefaultView;
            GridViewReportDetails.DataBind();
        }
        catch (Exception ex)
        {
            nResult = -1;
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.Master.SetMessage(ex.Message, true);

            GridViewReportDetails.SessionKey = "";
            GridViewReportDetails.SessionKeyIndex = 0;
            GridViewReportDetails.SessionKeyFilter = "";

            GridViewReportDetails.DataSource = new DataView();
            GridViewReportDetails.DataBind();
        }
        finally
        {
            lblReportTime.Text = " (" + Resources.GridView.ReportGenerateTime + " = " + dt2.Subtract(dt1).TotalSeconds.ToString("N4") + " sec)";
            if (nResult >= 0)
                foreach (DataTable dt in ds1.Tables)
                    nResult += dt.Rows.Count;
            Hipocrate.DB.DBConnection.Execute("InsertLOG", new string[] { "UserID", "RptID", "RptParams", "ExecutionTime", "Result" }, new object[] { this.UserIDx, strRptID, Tools.GetSQLValue(string.Join(",", arParamNamesAndValues2)), Convert.ToDecimal(dt2.Subtract(dt1).TotalSeconds), nResult });
        }

        lblRptID.Text = "RptID=" + strRptID;
        lblRptName2.Text = ds.Tables[0].DefaultView[0]["Name_" + Tools.GetLanguage(Request)].ToString();
        lblDescription2.Text = ds.Tables[0].DefaultView[0]["Description_" + Tools.GetLanguage(Request)].ToString();

        lblExplanations.Text = "\n<BR />" + string.Format(Resources.GridView.EXPL_LinesPerPage, Resources.GridView.LinesPerPage);
        lblExplanations.Text += "\n<BR />" + string.Format(Resources.GridView.EXPL_Filter, Resources.GridView.NoFilter);
        lblExplanations.Text += "\n<BR />" + Resources.GridView.EXPL_Excel;
        DataView dv = new DataView(((DataSet)Session["ds_ReportList"]).Tables[0]);
        foreach (DataRowView drv2 in dv2)
        {
            dv.RowFilter = "ID = " + drv2["TargetRptID"].ToString();
            if (dv.Count > 0)
                lblExplanations.Text += "\n<BR />" + string.Format(Resources.GridView.EXPL_Link, Tools.GetHeaderText(drv2["LinkColumn"].ToString()), dv[0]["Name_" + Tools.GetLanguage(Request)].ToString());
        }
        lblExplanations.Text += "\n";
    }

	private void CreateCriterias(string id, Table tblCriterias)
	{
		this.Context.Trace.Write("method called", "CreateCriterias");
		if (ViewState["Rows" + id] == null) return;

		HtmlGenericControl div = (HtmlGenericControl)(tblCriterias.Parent.FindControl("divParameter"));
		div.Style.Add("display", "");
		
		int rowCount = (int)ViewState["Rows" + id];
		System.Collections.Generic.List<string>[] controls = ViewState["Controls" + id] as System.Collections.Generic.List<string>[];
		if (rowCount != controls.Length)
			throw new ApplicationException("State mismatch.");
		if (rowCount == 0)
		{
			TableRow tr = new TableRow();
			tr.CssClass = "clsError";
			tblCriterias.Rows.AddAt(tblCriterias.Rows.Count, tr);
			TableCell td = new TableCell();
			tr.Cells.Add(td);
		}
		for (int i = 0; i < rowCount; ++i)
		{
			TableRow tr = new TableRow();
			tr.CssClass = "clsTableReportTr";
			tblCriterias.Rows.AddAt(tblCriterias.Rows.Count, tr);
			TableCell td = new TableCell(); //header
			td.CssClass = "RptCriteriaHeader";
			tr.Cells.Add(td);
			td = new TableCell(); //main area!
			tr.Cells.Add(td);
			if (controls[i]!=null)
			foreach (string controlId in controls[i])
			{
				this.Context.Trace.Write("adding control @ CreateCriterias", controlId);
				Control c = null;
				if (controlId.StartsWith("ddl"))
				{
					DropDownList list = new DropDownList();
					SetDefaultWidth(list);
					string[,] items = (string[,])(Application[string.Format("ReportList_{0}_{1}", id, i)]);
					for (int j = 0; j < (items.Length / 2); ++j)
					{
						string text = items[j, 0];
						string value = items[j, 1];
						list.Items.Add(new ListItem(text, value));
					}
					c = list;
				}
				else
					if (controlId.StartsWith("txt"))
					{
						TextBox input = new TextBox();
						SetDefaultWidth(input);
						tblCriterias.NamingContainer.Controls.Add(input); //ensure that it will be found
						c = input;
					}
					else
						if (controlId.StartsWith("calendar"))
						{
							CalendarExtender extender = new CalendarExtender();
							extender.TargetControlID = controlId.Replace("calendar_", "");
							//wishful thinking: extender.NamingContainer = td;
							//the current solution is to add the targetcontrol to the namingcontainer (which is the repeateritem), see 9 LoC above.
							extender.CssClass = "MyCalendar";
							c = extender;
						}
						else
							throw new ApplicationException("Unknown control type for: " + controlId);
				c.ID = controlId;
				td.Controls.Add(c);
			}
			td = new TableCell(); //third cell, containing the legend
			td.CssClass = "Explicatii";
			tr.Cells.Add(td);
		}
	}
	private void LoadCriterias(string id, Table tblCriterias)
    {
        try
        {
			ViewState["Rows" + id] = 0;
            if (Session["ds_ReportDetails"] == null)
                Response.Redirect("Reports.aspx");

            DataSet ds = (DataSet)Session["ds_ReportDetails"];
            DataView dv0 = ds.Tables[0].DefaultView;
            DataView dv1 = ds.Tables[1].DefaultView;
            DataView dv2 = ds.Tables[2].DefaultView;
            if (dv0.Count == 0)
                return;

            dv2.RowFilter = "[PARAMETER_NAME] <> '@RETURN_VALUE' AND [PARAMETER_NAME] <> '@TABLE_RETURN_VALUE' AND [PARAMETER_NAME] <> '@UserID'";
			ViewState["Rows" + id] = dv2.Count;
			System.Collections.Generic.List<string>[] controls = new System.Collections.Generic.List<string>[dv2.Count];

			TableRow tr = null;
            TableCell td = null;
            Control c = null;
			int i = 0;
			if (dv2.Count == 0)
			{
				tr = new TableRow();
				tr.CssClass = "clsError";
				tblCriterias.Rows.AddAt(tblCriterias.Rows.Count, tr);
				tblCriterias.Controls.Add(tr);

				td = new TableCell();
				tr.Cells.Add(td);
				td.Text = Resources.GridView.NoRecordFound;
			}
            foreach (DataRowView drv in dv2)
            {
				controls[i] = new System.Collections.Generic.List<string>();
                string strParameterName = drv["PARAMETER_NAME"].ToString().Substring(1);
                string strParameterType = drv["TYPE_NAME"].ToString();

                tr = new TableRow();
                tr.CssClass = "clsTableReportTr";
                tblCriterias.Rows.AddAt(tblCriterias.Rows.Count, tr);
                tblCriterias.Controls.Add(tr);

                td = new TableCell();
                tr.Cells.Add(td);
                td.CssClass = "RptCriteriaHeader";
                td.Wrap = false;
                td.Text = Tools.GetHeaderText(strParameterName);

				#region second cell: main control area
				td = new TableCell();
                tr.Cells.Add(td);
                td.Wrap = false;

                dv1.RowFilter = "[Column] = '" + strParameterName + "'";
                if (strParameterType == "bit")
                {
					DropDownList option = new DropDownList();
					option.ID = "ddl" + strParameterName;
					SetDefaultWidth(option);
					option.Items.Add(new ListItem("", ""));
					option.Items.Add(new ListItem(Resources.GridView.No, "0"));
					option.Items.Add(new ListItem(Resources.GridView.Yes, "1"));
					Application[string.Format("ReportList_{0}_{1}", id, i)] = GetDDLItems(option);
					c = option;
                }
                else if (dv1.Count == 0)
                {
					TextBox input = new TextBox();
					input.ID = "txt" + strParameterName;
					SetDefaultWidth(input);
					c = input;
                }
                else
                {
					DropDownList list = new DropDownList();
					list.ID = "ddl" + strParameterName;
					SetDefaultWidth(list);
					int nDdl = GetTableNo(ds, 1, strParameterName);
                    if (nDdl >= 0)
						FillDropDownList(list, ds.Tables[3 + nDdl].DefaultView, Convert.ToBoolean(dv1[0]["Translated"]), strParameterName);
					Application[string.Format("ReportList_{0}_{1}", id, i)] = GetDDLItems(list);
					c = list;
                }
                td.Controls.Add(c);
				controls[i].Add(c.ID);
				#endregion

				#region third cell: text that would detail the type and format of the required input
				td = new TableCell();
                tr.Cells.Add(td);
                td.CssClass = "Explicatii";
                td.Wrap = false;

                switch (strParameterType)
                {
                    case "bit":
                        td.Text = " (" + Resources.GridView.Type_Bit + ")";
                        break;
                    case "bigint":
                    case "int":
                    case "smallint":
                    case "tinyint":
                        td.Text = " (" + Resources.GridView.Type_Int + ")";
                        break;
                    case "decimal":
                    case "numeric":
                    case "float":
                    case "real":
                    case "money":
                    case "smallmoney":
                        td.Text = " (" + Resources.GridView.Type_Decimal + ")";
                        break;
                    case "datetime":
                    case "smalldatetime":
                        td.Text = " (" + Resources.GridView.Type_Date + " " + Tools.GetDateFormat() + ")";

						(c as TextBox).ToolTip = "Show Calendar";
						CalendarExtender ce = new CalendarExtender();
						ce.ID = "calendar_" + c.ID;
                        ce.TargetControlID = c.ID;
						ce.CssClass = "MyCalendar";
                        ce.Format = Tools.GetDateFormat();
                        c.Parent.Controls.Add(ce);
						controls[i].Add(ce.ID);
						break;
                    case "varchar":
                    case "char":
                    case "text":
                    case "nvarchar":
                    case "nchar":
                    case "ntext":
                        td.Text = " (" + Resources.GridView.Type_Text + ")";
                        break;
                    default:
                        td.Text = " (" + strParameterType + ")";
                        break;
                }
                if (c is DropDownList)
                    td.Text = " (" + Resources.GridView.Type_List + ")";
				#endregion
				++i;
            }
			ViewState["Controls" + id] = controls;
        }
        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
            this.SetMessage(ex.Message, true);
        }
    }

	private void SetDefaultWidth(WebControl target)
	{
		target.Width = Unit.Pixel(300);
	}
	private string[,] GetDDLItems(DropDownList source)
	{
		string[,] result = new string[source.Items.Count, 2];
		for (int i = 0; i < source.Items.Count; ++i)
		{
			result[i, 0] = source.Items[i].Text;
			result[i, 1] = source.Items[i].Value;
		}
		return result;
	}

	private void FillDropDownList(DropDownList d, DataView dv, bool bTranslated, string parameterName)
    {
        d.Items.Clear();
        foreach (DataRowView drv in dv)
        {
            ListItem li = new ListItem(bTranslated ? Tools.GetHeaderText(drv[parameterName].ToString()) : drv[parameterName].ToString(), drv["ID"].ToString());
            d.Items.Add(li);
        }
        d.Items.Insert(0, new ListItem("", ""));
    }

    private int GetTableNo(DataSet ds, int nParamsTable, string strParameterName)
    {
        DataView dv = new DataView(ds.Tables[nParamsTable], "Column = '" + strParameterName + "'", "", DataViewRowState.OriginalRows);
        if (dv.Count > 0)
            return dv.Table.Rows.IndexOf(dv[0].Row);
        else
            return -1;
    }

    private int GetProcedureType(string strProcedureName, string strDatabaseName)
    {
        int nProcedureType = 0;
        DataSet dsType = Hipocrate.DB.DBConnection.GetData("sp_help", new string[] { "objname" }, new object[] { Tools.GetSQLValue(strProcedureName) }, strDatabaseName, 1);
        switch (dsType.Tables[0].DefaultView[0]["Type"].ToString())
        {
            case "view":
            case "user table":
            case "internal table":
            case "system table":
                nProcedureType = 0;
                break;
            case "stored procedure":
            case "extended stored proc":
                nProcedureType = 1;
                break;
            case "inline function":
            case "scalar function":
            case "table function":
                nProcedureType = 2;
                break;
        }
        return nProcedureType;
    }

	private string[] emptyArray = new string[] { };
    private void LoadReportsCustom(object sender)
    {
        try
        {
			DataSet ds_Forum = Hipocrate.DB.DBConnection.GetData("ReportsCustom_Select", emptyArray, emptyArray);
            DataView dv = ds_Forum.Tables[3].DefaultView;

            if (dv.Count > 0)
            {
				ParentRepeaterEdit.DataSource = dv;
				ParentRepeaterEdit.DataBind();
				ViewState["reportIds"] = ids;

				rptParentView.DataSource = dv;
				rptParentView.DataBind();
            }
        }

        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.SetMessage(ex.Message, true);
		}
    }

	/// <summary>
	/// Loads the types of exports available, from the db table EXPORT_TYPES
	/// </summary>
    private void LoadDropDown(DropDownList target, string selectedValue)
	{
        try
        {
			DataSet ds_Types = Hipocrate.DB.DBConnection.GetData("EXPORT_TYPE_Select", emptyArray, emptyArray);
			DataView dv = ds_Types.Tables[1].DefaultView;

            if (dv.Count > 0)
            {
				target.DataSource = dv;
				target.DataTextField = "Name";
				target.DataValueField = "ID";
				target.DataBind();

				string selectedText = dv[0]["Name"].ToString();
				foreach (ListItem li in target.Items)
                {
					if (selectedValue == null)
					{
						if (li.Text.Equals(selectedText, StringComparison.CurrentCultureIgnoreCase))
							target.SelectedValue = li.Value;
					}
					else
					{
						if (li.Value.Equals(selectedValue, StringComparison.CurrentCultureIgnoreCase))
							target.SelectedValue = li.Value;
					}
				}
            }
		}
        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.SetMessage(ex.Message, true);
		}
    }

    protected void btnSaveReport_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtName.Text == "")
            {
                txtName.BackColor = System.Drawing.Color.Pink;
                this.SetMessage("Nu ai introdus numele.", true);
                return;
            }
            txtName.BackColor = System.Drawing.Color.White;
            string explicatie;
            if (!ValidateColSpan(txtColumnSpanEnumeration.Text, out explicatie))
            {
                txtColumnSpanEnumeration.BackColor = System.Drawing.Color.Pink;
                this.SetMessage(explicatie, true);
                return;
            }
            txtColumnSpanEnumeration.BackColor = System.Drawing.Color.White;
            DataSet ds_ReportInsert = Hipocrate.DB.DBConnection.GetData("ReportCustom_Insert", new string[] { "Name", "DatabaseName", "ProcedureName", "TypeID", "Header", "Title", "Footer", "EnableColumnSpan", "EnableColumnFormula", "EnableColumnTotal", "MultipleReports", "ColumnSpanEnumeration", "ColumnName", "ColumnSum", "ColumnFormula", "ColumnSpanTitle", "HiddenColumns" },
                new object[] { txtName.Text, txtDatabase.Text, txtProcedure.Text, drpCategory.SelectedValue, txtHeader.Text, txtTitle.Text, txtFooter.Text, chkColumnSpan.Checked, chkColumnFormula.Checked, chkEnableColumnSum.Checked, chkMultiReports.Checked, txtColumnSpanEnumeration.Text, txtColumnName.Text, txtColumnSum.Text, txtFormula.Text, txtSpanTitle.Text, txtHiddenColumns.Text });
            LoadReportsCustom(null);
            this.SetMessage("Saved.", false);
        }
        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.SetMessage(ex.Message, true);
		}
    }

    protected void btnReconfigure_Click(object sender, EventArgs e)
    {
        try
        {
            Label ls = (Label)((System.Web.UI.WebControls.RepeaterItem)((System.Web.UI.Control)(sender)).Parent).Controls[3];
            this.TempID = ls.Text;
            modalReconfigure.Show();

            DataSet ds_Forum = Hipocrate.DB.DBConnection.GetData("ReportsCustom_Select", new string[] { "ID" }, new object[] { this.TempID });
            DataView dv0 = ds_Forum.Tables[1].DefaultView;

            if (dv0[0]["Name"] != System.DBNull.Value)
                txtNameRec.Text = dv0[0]["Name"].ToString();
            if (dv0[0]["EnableColumnSpan"] != System.DBNull.Value)
            {
                chkColumnSpanRec.Checked = Convert.ToBoolean(dv0[0]["EnableColumnSpan"]);
                CheckSpanRec_Clicked(null, null);
            }
            if (dv0[0]["DatabaseName"] != System.DBNull.Value)
                txtDatabaseRec.Text = dv0[0]["DatabaseName"].ToString();
            if (dv0[0]["ColumnSpanEnumeration"] != System.DBNull.Value)
                txtColumnSpanEnumerationRec.Text = dv0[0]["ColumnSpanEnumeration"].ToString();
            if (dv0[0]["ProcedureName"] != System.DBNull.Value)
                txtProcedureRec.Text = dv0[0]["ProcedureName"].ToString();
            if (dv0[0]["ColumnName"] != System.DBNull.Value)
                txtColumnNameRec.Text = dv0[0]["ColumnName"].ToString();
            if (dv0[0]["ColumnSum"] != System.DBNull.Value)
                txtColumnSumRec.Text = dv0[0]["ColumnSum"].ToString();
            if (dv0[0]["TypeID"] != System.DBNull.Value)
				LoadDropDown(drpCategoryRec, dv0[0]["TypeID"].ToString());

            if (dv0[0]["ColumnFormula"] != System.DBNull.Value)
                txtFormulaRec.Text = dv0[0]["ColumnFormula"].ToString();

            if (dv0[0]["EnableColumnFormula"] != System.DBNull.Value)
                chkColumnFormulaRec.Checked = Convert.ToBoolean(dv0[0]["EnableColumnFormula"]);

            if (dv0[0]["ColumnSpanTitle"] != System.DBNull.Value)
                txtSpanTitleRec.Text = dv0[0]["ColumnSpanTitle"].ToString();

            if (dv0[0]["EnableColumnTotal"] != System.DBNull.Value)
                chkEnableColumnSumRec.Checked = Convert.ToBoolean(dv0[0]["EnableColumnTotal"]);

            if (dv0[0]["Header"] != System.DBNull.Value)
            {
                txtHeaderRec.Text = HttpUtility.HtmlDecode(dv0[0]["Header"].ToString());
            }

            if (dv0[0]["Title"] != System.DBNull.Value)
                txtTitleRec.Text = HttpUtility.HtmlDecode(dv0[0]["Title"].ToString());

            if (dv0[0]["Footer"] != System.DBNull.Value)
                txtFooterRec.Text = HttpUtility.HtmlDecode(dv0[0]["Footer"].ToString());

            if (dv0[0]["MultipleReports"] != System.DBNull.Value)
                chkMultiReportsRec.Checked = Convert.ToBoolean(dv0[0]["MultipleReports"]);

            if (dv0[0]["HiddenColumns"] != System.DBNull.Value)
                txtHiddenColumnsRec.Text = HttpUtility.HtmlDecode(dv0[0]["HiddenColumns"].ToString());

        }
        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.SetMessage(ex.Message, true);
		}
    }

    protected void btnUpdateReport_Click(object sender, EventArgs e)
    {
        try
        {
            string explicatie;
            if (!ValidateColSpan(txtColumnSpanEnumerationRec.Text, out explicatie))
            {
                txtColumnSpanEnumerationRec.BackColor = System.Drawing.Color.Pink;
                this.SetMessage(explicatie, true);
                modalReconfigure.Show();
                return;
            }
            txtColumnSpanEnumerationRec.BackColor = System.Drawing.Color.White;
            DataSet ds_Update = Hipocrate.DB.DBConnection.GetData("ReportCustom_Update", new string[] { "ID", "Name", "DatabaseName", "ProcedureName", "TypeID", "Header", "Title", "Footer", "EnableColumnSpan", "EnableColumnFormula", "EnableColumnTotal", "MultipleReports", "ColumnSpanEnumeration", "ColumnName", "ColumnSum", "ColumnFormula", "ColumnSpanTitle", "HiddenColumns" }, new object[] { 
                this.TempID, txtNameRec.Text, txtDatabaseRec.Text, txtProcedureRec.Text, drpCategoryRec.SelectedValue, txtHeaderRec.Text, txtTitleRec.Text, txtFooterRec.Text, chkColumnSpanRec.Checked, chkColumnFormulaRec.Checked, chkEnableColumnSumRec.Checked,chkMultiReportsRec.Checked, txtColumnSpanEnumerationRec.Text, txtColumnNameRec.Text, txtColumnSumRec.Text, txtFormulaRec.Text, txtSpanTitleRec.Text, txtHiddenColumnsRec.Text });
            this.SetMessage("Updated.", false);
        }
        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.SetMessage(ex.Message, true);
		}
    }

    private string StripTags(string HTML)
    {
        System.Text.RegularExpressions.Regex objRegEx = new System.Text.RegularExpressions.Regex("<[^>]*>");
        return objRegEx.Replace(HTML, "");
    }

    protected void btnExportSIUI_Click(object sender, EventArgs e)
    {
		try
		{
			RepeaterItem container = (System.Web.UI.WebControls.RepeaterItem)(((System.Web.UI.Control)sender).Parent);
			DropDownList drp = (DropDownList)(container.FindControl("drpTypeExport"));
			Label lit = (Label)(container.FindControl("lblID"));
			string idLabel = lit.Text;
			string queryString = "?id=" + idLabel + "&startDate=" + txtStart_Date.Text + "&endDate=" + txtEnd_Date.Text;

			#region new	queryString
			Hashtable ht = Tools.GetControlValues((Table)(container.FindControl("tblCriterias")));
			queryString = "?id=" + idLabel;
			foreach (object obj in ht.Keys)
				queryString += string.Format("&{0}={1}" , obj, ((string[])(ht[obj]))[0]);
			#endregion

			string typeDrop = drp.SelectedValue.ToString();

			string targetUrl = null;
			switch (typeDrop)
			{
				case "PDF":
				case "Word":
				case "Excel":
					targetUrl = string.Format("~/Tools/Export{0}.ashx", typeDrop);
					break;
				default:
					//return;
					break;
			}
			if (targetUrl != null)
				Page.Response.Redirect(targetUrl + queryString, false);
		}
		catch (Exception ex)
		{
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.Master.SetMessage(ex.Message, true);
		}
    }

    protected void Check_Clicked(object sender, EventArgs e)
    {
        if (!bChecked)
        {
            chkColumnFormula.Enabled = false;
            chkEnableColumnSum.Enabled = false;
            chkColumnSpan.Enabled = false;
            txtColumnSpanEnumeration.Enabled = false;
            txtColumnSum.Enabled = false;
            txtFormula.Enabled = false;
            txtSpanTitle.Enabled = false;

            bChecked = true;
        }
        else
        {
            chkColumnFormula.Enabled = true;
            chkEnableColumnSum.Enabled = true;
            chkColumnSpan.Enabled = true;
            txtColumnSpanEnumeration.Enabled = true;
            txtColumnSum.Enabled = true;
            txtFormula.Enabled = true;
            txtSpanTitle.Enabled = true;

            bChecked = false;
        }
    }

    protected void CheckSum_Clicked(object sender, EventArgs e)
    {
		bCheckedSum = !bCheckedSum;
		txtColumnSum.Enabled = bCheckedSum;
	}

    protected void CheckFormula_Clicked(object sender, EventArgs e)
    {
		bCheckedFormula = !bCheckedFormula;
		txtFormula.Enabled = bCheckedFormula;
	}

    protected void CheckSpan_Clicked(object sender, EventArgs e)
    {
        if (!bCheckedSpan)
        {
            txtSpanTitle.Enabled = true;
            txtColumnSpanEnumeration.Enabled = true;
            bCheckedSpan = true;
            trDetaliiColSpan.Controls.Add(trDetaliiColSpanRec.Controls[0]);
            trDetaliiColSpan.Visible = true;
        }
        else
        {
            txtSpanTitle.Enabled = false;
            txtColumnSpanEnumeration.Enabled = false;
            bCheckedSpan = false;
            trDetaliiColSpan.Visible = false;
        }
    }

    protected void CheckSpanRec_Clicked(object sender, EventArgs e)
    {
        modalReconfigure.Show();
        txtSpanTitleRec.Enabled = chkColumnSpanRec.Checked;
        txtColumnSpanEnumerationRec.Enabled = chkColumnSpanRec.Checked;
        labelDetaliiColSpanRec.Visible = chkColumnSpanRec.Checked;
        trDetaliiColSpanRec.Visible = chkColumnSpanRec.Checked;
        UpReconfigure.Update();
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            Label ls = (Label)((System.Web.UI.WebControls.RepeaterItem)((System.Web.UI.Control)(sender)).Parent).Controls[3];
            this.TempID = ls.Text;
            DataSet ds_Forum = Hipocrate.DB.DBConnection.GetData("ReportCustom_Delete", new string[] { "ID" }, new object[] { this.TempID });
            this.SetMessage("Deleted.", false);
        }
        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.SetMessage(ex.Message, true);
		}
    }

	private System.Collections.Generic.List<string> ids = new System.Collections.Generic.List<string>();
	protected void ParentRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
		this.Context.Trace.Write("event handler triggered", "ParentRepeater_ItemDataBound");
		RepeaterItem item = e.Item;
		if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater ChildRepeater = (Repeater)item.FindControl("ChildRepeater");
            DataRowView drv = (DataRowView)item.DataItem;

            DataSet ds_Forum = Hipocrate.DB.DBConnection.GetData("ReportsCustom_Select", new string[] { "TypeID" }, new object[] { drv["ID"].ToString() });
            DataView dv = ds_Forum.Tables[2].DefaultView;
			foreach (DataRowView cursor in dv) ids.Add(cursor["ID"].ToString());
            ChildRepeater.DataSource = dv;
            ChildRepeater.DataBind();
        }
    }

    protected void rptChild_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
		this.Context.Trace.Write("event handler triggered", "rptChild_ItemDataBound");
		RepeaterItem item = e.Item;
		if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
        {
			Button btn = (Button)(e.Item.FindControl("btnParameter"));
            DataRowView drv = (DataRowView)e.Item.DataItem;
            btn.CommandArgument = drv["ID"].ToString();
        }
    }

	private int idIndex = 0;
	protected void rptChild_ItemCreated(object sender, RepeaterItemEventArgs e)
	{
		this.Context.Trace.Write("event handler triggered", "rptChild_ItemCreated @" + e.Item.ItemIndex);
		RepeaterItem item = e.Item;
		if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
		{
			try
			{
				if (ids.Count == 0)
					ids = (System.Collections.Generic.List<string>)ViewState["reportIds"];
				CreateCriterias(ids[idIndex++], (Table)(e.Item.FindControl("tblCriterias")));
			}
			catch (Exception ex)
			{
				startDate.Text += "<!-- " + ex.ToString() + " -->";
				this.SetMessage(ex.Message, true);
				//throw new ApplicationException(ex.ToString());
			}
		}
	}

	protected void btnEditParameter_Click(object sender, EventArgs e)
    {
		this.Context.Trace.Write("event handler called", "btnEditParameter_Click");
		Button btn = (sender as Button);
        HtmlGenericControl div = (HtmlGenericControl)(btn.Parent.FindControl("divParameter"));
		div.Style.Add("display", "");
		LinkButton popup = (LinkButton)(btn.Parent.FindControl("hpLnk"));
		popup.Enabled = true;
		Button export = (Button)(btn.Parent.FindControl("btnExport"));
		export.Visible = true;
		HtmlControl verticalSpace = (HtmlControl)(btn.Parent.FindControl("verticalSpace"));
		verticalSpace.Visible = true;

		Table tbl = (Table)(btn.Parent.FindControl("tblCriterias"));
		//int rptID = Convert.ToInt32(btn.CommandArgument);
		DoSelectReport(btn.CommandArgument, tbl);

		//try
		{
			bool allowsPdf = true;
			if ((Session["ds_ReportDetails"] as DataSet).Tables[0].Columns.Contains("CustomReports"))
			{
				object custom = (Session["ds_ReportDetails"] as DataSet).Tables[0].Rows[0]["CustomReports"];
				allowsPdf &= !((custom != DBNull.Value) && (custom != null) && (custom.ToString().Trim().Length > 0));
			}
			if ((Session["ds_ReportDetails"] as DataSet).Tables[0].Columns.Contains("MultipleReports"))
			{
				object multiple = (Session["ds_ReportDetails"] as DataSet).Tables[0].Rows[0]["MultipleReports"];
				allowsPdf &= !((multiple != DBNull.Value) && (multiple != null) && (Convert.ToBoolean(multiple) == true));
			}
			if (!allowsPdf)
			{
				DropDownList drpTypeExport = (DropDownList)(btn.Parent.FindControl("drpTypeExport"));
				foreach (ListItem item in drpTypeExport.Items)
					if (item.Value.Equals("PDF"))
					{
						drpTypeExport.Items.Remove(item);
						break;
					}
			}
		}
		//catch(Exception ex)
		//{
		//    throw new ApplicationException(ex.ToString());
		//}

		btn.Enabled = false;
    }

    private bool ValidateColSpan(string text, out string explicatie)
    {
        string[] parts = text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        int max = 0;
        foreach (string s in parts)
        {
            string colNumber = (s.Contains(":") ? s.Split(':')[0] : s);
            int n;
            if (!int.TryParse(colNumber, out n)) { explicatie = "Numarul coloanei '" + colNumber + "' este invalid!"; return false; }
            if (n <= max) { explicatie = "Coloanele defalcate trebuie ordonate crescator!"; return false; }
            max = n;
        }
        explicatie = "";
        return true;
    }

    protected void btnViewReport_Click(object sender, EventArgs e)
    {
		//NB: also sends params that were NOT filled... :)
		try
        {
            LinkButton lnkBtn = (sender as LinkButton);
			Table tbl = (Table)(lnkBtn.Parent.FindControl("tblCriterias"));
            string rptID = (sender as LinkButton).CommandArgument;
            Hashtable ht = Tools.GetControlValues(tbl);
			ht.Add("id", new string[] { rptID, null });

			ScriptManager.RegisterArrayDeclaration(this, "nParamsCount", ht.Keys.Count.ToString());
			string paramNames = "", paramValues = "";
			foreach (object obj in ht.Keys)
			{
				string quoted = string.Format("'{0}'", obj);
				//"this.Page.ClientScript." doesn't work...
				ScriptManager.RegisterArrayDeclaration(this, "paramName", quoted);
				paramNames += ", " + quoted;
				quoted = string.Format("'{0}'", ((string[])(ht[obj]))[0]);
				ScriptManager.RegisterArrayDeclaration(this, "paramValue", quoted);
				paramValues += ", " + quoted;
			}
			paramNames = "new Array(" + paramNames.Substring(1) + " )";
			paramValues = "new Array(" + paramValues.Substring(1) + " )";

			string js = "ShowReportExtended();";
			ScriptManager.RegisterStartupScript(this, typeof(Hipocrate_Reports), "previewReport", js, true);
        }
        catch (Exception ex)
        {
			startDate.Text += "<!-- " + ex.ToString() + " -->";
			this.SetMessage(ex.Message, true);
		}
    }
}
